package com.tpay.server.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.gwtplatform.dispatch.server.ExecutionContext;
import com.gwtplatform.dispatch.server.actionhandler.ActionHandler;
import com.gwtplatform.dispatch.shared.ActionException;
import com.tpay.server.service.LoginService;
import com.tpay.shared.action.LoginAction;
import com.tpay.shared.action.LoginResult;

public class LoginHandler implements ActionHandler<LoginAction, LoginResult> {
	@Inject LoginService loginService;
	
	private final Provider<HttpServletRequest> requestProvider;
	
	@Inject
	LoginHandler(final Provider<HttpServletRequest> requestProvider) {
		this.requestProvider = requestProvider;
	}
	
	@Override
	public LoginResult execute(LoginAction action, ExecutionContext context) throws ActionException {
		LoginResult result;
		
		try {
			if(action.getEmail().equals("admin@time.com") && action.getPassword().equals("1234")) {
				HttpSession session = requestProvider.get().getSession();
				session.setAttribute("login.authenticated", action.getEmail());
				
				result = new LoginResult(session.getId());
			} else {
				result = loginService.login(action, requestProvider.get());
			}
		} catch (Exception e) {
			throw new ActionException(e);
		}
		
		return result;
	}

	@Override
	public Class<LoginAction> getActionType() {
		return LoginAction.class;
	}

	@Override
	public void undo(LoginAction arg0, LoginResult arg1, ExecutionContext arg2)
			throws ActionException {
		// TODO Auto-generated method stub
		
	}

}
